use std::rc::Rc;
use yew::{function_component, html, use_state, Callback, Children, Component, Context, ContextProvider, Html, Properties};

pub struct MainView {
    state: Rc<AppState3>,
}

#[derive(Clone, Properties, PartialEq)]
pub struct MainProps {
    pub children: Children
}

pub enum MainMsg {
    ButtonClick,
}

impl Component for MainView {
    type Message = MainMsg;
    type Properties = MainProps;

    fn create(_ctx: &Context<Self>) -> Self {
        let state = Rc::new(AppState3 { total: 0 });
        Self { state }
    }

    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            MainMsg::ButtonClick => {
                Rc::make_mut(&mut self.state).total += 1;
                true
            }
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let state = self.state.clone();
        let onclick = ctx.link().callback(|_| MainMsg::ButtonClick);

        let app_state = self.state.clone();
        html! {
           <ContextProvider<Rc<AppState3>> context={ state }>
                <button {onclick}> { " increase:  "} { app_state.total }</button>

                { for ctx.props().children.iter() }

            </ContextProvider<Rc<AppState3>>>
        }
    }
}


#[derive(Clone, PartialEq)]
pub struct AppState3 {
    // websocket_handle: Option<UseWebSocketHandle>,
    total: u32,
}

#[function_component]
pub fn MainView2(props: &MainProps)->Html {
    let state = use_state(|| {AppState3 { total: 0 }});

    let onclick = Callback::from({
        let counter = state.clone();
        move |_| {
            let new_value = counter.total + 1;
            counter.set(AppState3 {total: new_value})
        }
    });
    html! {
       <ContextProvider<AppState3> context={ (*state).clone() }>
            <button {onclick}> { " increase:  "} { state.clone().total }</button>

            { for props.children.iter() }

        </ContextProvider<AppState3>>
    }
}